<template>
  <div class="go-to-review">
    <PageHeader title="发表评价" />
    <div class="review-form">
      <div v-for="(item, index) in order.items" :key="index" class="row">
        <van-row gutter="20">
          <van-col span="4">
            <van-image
                width="40px"
                height="40px"
                :src="item.product && item.product.imageUrl ? require('@/'+`${item.product.imageUrl}`) : require('@/assets/products/default.png')"
            />
          </van-col>
          <van-col span="8">
            <p style="font-size: 14px;color: grey;line-height: 40px">{{ item.product ? item.product.productName : '商品名称' }}</p>
          </van-col>
          <van-col span="12">
            <div class="star">
              <van-rate v-model="item.rating" />
            </div>
          </van-col>
        </van-row>
        <van-field
            v-model="item.reviewText"
            label="评价内容"
            type="textarea"
            placeholder="请输入评价内容"
        />
      </div>
      <div class="button">
        <van-button
            round
            style="height: 30px; border-color: #FA6408; color: #FA6408"
            @click="submitReview"
            class="submit-button"
        >
          提交
        </van-button>
      </div>
    </div>
  </div>
</template>

<script>
import PageHeader from "@/components/PageHeader.vue";
import { Row as VanRow, Col as VanCol, Image as VanImage, Rate as VanRate, Field as VanField, Button as VanButton } from 'vant';
import http from "@/plugins/http";

export default {
  name: "GoReviewView",
  components: {
    PageHeader,
    VanRow,
    VanCol,
    VanImage,
    VanRate,
    VanField,
    VanButton
  },
  data() {
    return {
      rating: 0,
      reviewText: '',
      order: {
       items:[]
      },
      username: '', // 替换为当前登录用户的用户名
    };
  },
  activated() {
    this.username=localStorage.getItem("username")
    const orderId = this.$route.params.orderId;
    this.fetchOrders(orderId);
    this.fetchUserInfo();
  },
  methods: {
    submitReview() {
      this.order.items.forEach((item) => {
        const reviewData = {
          productId: item.productId, // 对应当前商品的 productId
          username: this.username, // 当前登录用户
          rating: item.rating, // 用户对该商品的评分
          comment: item.reviewText, // 用户对该商品的评价
        };
        console.log("reviewData:", reviewData);

        // 对每个商品的评价进行单独提交
        http.post('/review/add', reviewData)
            .then(() => {
              this.$toast.success('评价提交成功');
              this.updateOrderStatus(); // 更新订单状态
            })
            .catch(() => {
              this.$toast.fail('评价提交失败');
            });
      });
    },
    fetchOrders(orderId) {
      if (orderId) {
        http.get(`/items/getById/${orderId}`)
            .then(response => {
              if (response.statusCode === '200') {
                // 假设 response.data 直接是商品的数组
                this.order = {
                  items: response.data
                };
                console.log("this.order:"+this.order);
              } else {
                console.log("订单出错");
              }
            })
            .catch(error => {
              console.error("获取订单信息出错:", error);
            });
      } else {
        console.log("没有订单");
      }
    },
    updateOrderStatus() {
      const orderId = this.$route.params.orderId;
      http.post('/order/updateOrder', {
        orderId: orderId,
        status: 5,
      })
          .then(() => {
            this.$toast.success('订单状态已更新');
            this.$router.go(-1);
          })
          .catch(() => {
            this.$toast.fail('订单状态更新失败');
          });
    },
    fetchUserInfo() {
      this.username = JSON.parse(sessionStorage.getItem("username"));
    },
  }
};
</script>

<style scoped>
.go-to-review {
  background-color: #F6F7F9;
  height: 100vh;
}

.review-form {
  background-color: white;
  padding: 20px;
}

.row {
  margin-bottom: 20px;
}
.submit-button
{
  margin-top:10px;
  margin-left:230px;
}
.star
{
  margin-top:10px;
}
</style>
